package com.qiangesoft.rdp.starter.mvc.response;

import com.qiangesoft.rdp.starter.mvc.exception.result.ExceptionResultHandler;
import com.qiangesoft.rdp.starter.mvc.exception.result.ResultMessageEnum;
import lombok.Getter;
import lombok.Setter;

import java.io.Serializable;

/**
 * 响应信息主体
 *
 * @author qiangesoft
 * @date 2023-09-18
 */
@Getter
@Setter
public class ResponseInfo<T> implements Serializable {

    private static final long serialVersionUID = 1L;

    private int code;

    private String message;

    private T data;

    private long timestamp;

    public static ResponseInfo success() {
        return buildResponse(ResultMessageEnum.SUCCESS.getCode(), ResultMessageEnum.SUCCESS.getMessage(), null);
    }

    public static <T> ResponseInfo<T> success(T data) {
        return buildResponse(ResultMessageEnum.SUCCESS.getCode(), ResultMessageEnum.SUCCESS.getMessage(), data);
    }

    public static <T> ResponseInfo<T> success(String message, T data) {
        return buildResponse(ResultMessageEnum.SUCCESS.getCode(), message, data);
    }

    public static ResponseInfo fail() {
        return buildResponse(ResultMessageEnum.FAIL.getCode(), ResultMessageEnum.FAIL.getMessage(), null);
    }

    public static ResponseInfo fail(ExceptionResultHandler exceptionAdvice) {
        return buildResponse(exceptionAdvice.getCode(), exceptionAdvice.getMessage(), null);
    }

    public static ResponseInfo fail(String message) {
        return buildResponse(ResultMessageEnum.FAIL.getCode(), message, null);
    }

    public static ResponseInfo fail(int code, String message) {
        return buildResponse(code, message, null);
    }

    public static <T> ResponseInfo<T> fail(String message, T data) {
        return buildResponse(ResultMessageEnum.FAIL.getCode(), message, data);
    }

    public static <T> ResponseInfo<T> fail(int code, String message, T data) {
        return buildResponse(code, message, data);
    }

    private static <T> ResponseInfo<T> buildResponse(int code, String message, T data) {
        ResponseInfo<T> responseInfo = new ResponseInfo<>();
        responseInfo.setCode(code);
        responseInfo.setMessage(message);
        responseInfo.setData(data);
        responseInfo.setTimestamp(System.currentTimeMillis());
        return responseInfo;
    }

    public static <T> Boolean isFail(ResponseInfo<T> responseInfo) {
        return !isSuccess(responseInfo);
    }

    public static <T> Boolean isSuccess(ResponseInfo<T> responseInfo) {
        return ResultMessageEnum.SUCCESS.getCode() == responseInfo.getCode();
    }
}
